package com.example.smartcity_poverty.ui.AllService.GovernmentHotLine

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.MenuItem
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.smartcity_poverty.App.Companion.context
import com.example.smartcity_poverty.App.Companion.getToken
import com.example.smartcity_poverty.App.Companion.url
import com.example.smartcity_poverty.Base.BaseRecyclerAdapter
import com.example.smartcity_poverty.R
import com.example.smartcity_poverty.logic.Repository.api
import com.example.smartcity_poverty.logic.model.GovernmentHotLine.GmHotLineBannerModel
import com.example.smartcity_poverty.logic.model.GovernmentHotLine.GmHotLineMeAllModel
import com.example.smartcity_poverty.logic.model.GovernmentHotLine.GmHotLineMoreModel
import com.example.smartcity_poverty.logic.util.Util.glide
import com.example.smartcity_poverty.logic.util.Util.show
import com.example.smartcity_poverty.logic.util.Util.startActivityUtils
import com.example.smartcity_poverty.ui.AllService.GovernmentHotLine.Activity.AddGmHotLineActivity
import com.example.smartcity_poverty.ui.AllService.GovernmentHotLine.Activity.GmHotLineShowListActivity
import com.example.smartcity_poverty.ui.AllService.GovernmentHotLine.Activity.ShowGmHotLineUserAllActivity
import com.example.smartcity_poverty.ui.PersonalCenter.activity.LoginActivity
import com.youth.banner.adapter.BannerImageAdapter
import com.youth.banner.holder.BannerImageHolder
import com.youth.banner.indicator.CircleIndicator
import kotlinx.android.synthetic.main.activity_gm_hot_line.*
import kotlinx.android.synthetic.main.re_gmhotline_me_list_all.*
import kotlinx.android.synthetic.main.re_gmhotline_more.*
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

/**
 * 政府服务热线
 */
class GmHotLineActivity : AppCompatActivity() {

    val token = getToken()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        setContentView(R.layout.activity_gm_hot_line)
        title = "政府服务热线"


        // 轮播图适配
        setBanner()

        // 市民诉求分类
        setMore()

        // 我的诉求
        setMeList()
    }

    /**
     * 我的诉求
     */
    private fun setMeList() {
        if (token.isNotEmpty()) {
            CoroutineScope(Dispatchers.Main).launch {
                api.getGmHotLineMeListAll(token).apply {
                    if (this.code == 200) {
                        val rows = this.rows
                        gmMeListAllRv.apply {
                            this.layoutManager = LinearLayoutManager(context)
                            this.adapter = MeListAdapter(
                                ArrayList<GmHotLineMeAllModel.RowsBean>().apply {
                                    this.addAll(rows!!)
                                },
                                R.layout.re_gmhotline_me_list_all
                            )
                            this.isNestedScrollingEnabled = false
                        }
                    } else runOnUiThread { "加载诉求出错！".show() }
                }
            }
        } else "请先登录！".show()
    }

    /**
     * 市民诉求分类
     */
    private fun setMore() {
        if (token.isNotEmpty()) {
            CoroutineScope(Dispatchers.Main).launch {
                api.getGmHotLineMoreAll(token).apply {
                    if (this.code == 200) {
                        val rows = this.rows
                        runOnUiThread {
                            gmMoreRv.apply {
                                this.layoutManager = GridLayoutManager(context, 2).apply {
                                    this.orientation = GridLayoutManager.HORIZONTAL

                                }
                                this.adapter =
                                    GmMoreAdapter(ArrayList<GmHotLineMoreModel.RowsBean>().apply {
                                        this.addAll(rows!!)
                                    }, R.layout.re_gmhotline_more)
                                this.isNestedScrollingEnabled = false

                            }
                        }
                    } else runOnUiThread { "加载服务失败！".show() }
                }
            }
            // 如果token为空， 侧跳转到登录页面
        } else {
            // 先销毁意图
            finish()
            // 启动登录界面
            startActivityUtils(context, LoginActivity())
        }
    }

    /**
     * 轮播图适配器
     */
    private fun setBanner() {
        if (token.isNotEmpty()) {
            CoroutineScope(Dispatchers.Main).launch {
                api.getGmHotLineBanner(token).apply {
                    if (this.code == 200) {
                        val data = this.data
                        runOnUiThread {
                            gmBanner.apply {
                                this.adapter = object :
                                    BannerImageAdapter<GmHotLineBannerModel.DataBean>(data) {
                                    override fun onBindView(
                                        p0: BannerImageHolder?,
                                        p1: GmHotLineBannerModel.DataBean?,
                                        p2: Int,
                                        p3: Int
                                    ) {
                                        glide(url + p1?.imgUrl, p0?.imageView!!)
                                    }
                                }
                                this.addBannerLifecycleObserver(this@GmHotLineActivity).indicator =
                                    CircleIndicator(context)
                                this.setBannerRound(25f)
                            }
                        }
                    } else runOnUiThread { "加载网络失败！".show() }
                }
            }
        } else "请先登录!".show()
    }


    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        finish()
        return super.onOptionsItemSelected(item)
    }

    /**
     * 适配器
     */
    companion object {
        // 政府服务热线服务模块适配器
        class GmMoreAdapter(
            val list: MutableList<GmHotLineMoreModel.RowsBean>,
            val layoutId: Int
        ) : BaseRecyclerAdapter<GmHotLineMoreModel.RowsBean>(list, layoutId) {
            override fun setData(
                view: BaseViewHolder.ViewFind,
                data: GmHotLineMoreModel.RowsBean,
                position: Int,
                holder: BaseViewHolder
            ) {
                // 按照优先级排序
                list.sortBy { it -> it.sort }

                val d = list[position]
                val fv = holder.viewFind
                val con = fv.view?.context

                glide(url + d.imgUrl, fv.GmHotLineMoreImage)
                fv.GmHotLineMoreTitle.text = d.name


                holder.itemView.setOnClickListener {
                    if (fv.GmHotLineMoreTitle.text.toString() == "其他诉求"){
                        con?.startActivity(Intent(con, AddGmHotLineActivity::class.java).apply {
                            putExtra("getVisId", 520)
                        })
                    }else con?.startActivity(Intent(con, GmHotLineShowListActivity::class.java).putExtra("id", d.id.toString()))

                }
            }

        }


        /**
         * TODO　我的诉求列表适配器
         */
        class MeListAdapter(
            val list: MutableList<GmHotLineMeAllModel.RowsBean>,
            val layoutId: Int
        ) : BaseRecyclerAdapter<GmHotLineMeAllModel.RowsBean>(list, layoutId) {
            override fun setData(
                view: BaseViewHolder.ViewFind,
                data: GmHotLineMeAllModel.RowsBean,
                position: Int,
                holder: BaseViewHolder
            ) {
                list.sortByDescending { it.createTime }
                val d = list[position]
                val fv = holder.viewFind
                val con = fv.context

                fv.gmMeTitle.text = d.title
                fv.gmMeUser.text = "承办单位:${d.undertaker}"
                if (d.state.toString() == "1") fv.gmMeIsOk.text = "处理状态:已处理"
                else fv.gmMeIsOk.text = "处理状态: 处理中"
                fv.gmMeTime.text = "提交时间: ${d.createTime}"

                holder.itemView.setOnClickListener {
                    // 点击进入诉求详情页
                    holder.viewFind.view?.context?.startActivity(Intent(
                        holder.viewFind.view?.context,
                        ShowGmHotLineUserAllActivity::class.java
                    ).apply {
                        putExtra("title", d.title.toString())
                        putExtra("image", d.imgUrl.toString())
                        putExtra("undertaker", d.undertaker.toString())
                        putExtra("state", d.state.toString())
                        putExtra("createTime", d.createTime.toString())
                        putExtra("detailResult", d.detailResult.toString())
                        putExtra("contend", d.content.toString())
                    })
                }

            }

        }
    }
}